package com.o2opuzi.lib.db;

import java.beans.PropertyDescriptor;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.util.StringUtils;


/**
 * 
 * @author Y.hj
 * @date 2016年5月31日
 */
public class TableMapping {
	
	/**
	 * 默认的id 名字
	 */
	private String id = "id";
	
	private String name;
	
	private boolean idAuto = true;
	
	private PropertyDescriptor idProperty;
		
	private List<PropertyDescriptor> columns = new ArrayList<PropertyDescriptor>();

	public TableMapping(Class<?> beanClass) {
		Tb tb = beanClass.getAnnotation(Tb.class);
		if(tb != null){
			this.name = tb.name();
			this.id = tb.id();
			this.idAuto = tb.idAuto();
		}
		if(StringUtils.isEmpty(this.name))
			this.name = beanClass.getSimpleName().toLowerCase();
		PropertyDescriptor[] pds = BeanUtils.getPropertyDescriptors(beanClass);
		for (PropertyDescriptor pd : pds) {
			if (pd.getReadMethod() != null && pd.getWriteMethod() != null && !pd.getName().equals("metaClass")) {
				if(pd.getName().equals(this.id)){
					setIdProperty(pd);
					continue;
				}
				columns.add(pd);	
			}
		}
	}

	public String getId() {
		return id;
	}

	public void setId(String id) {
		this.id = id;
	}

	public String getName() {
		return name;
	}

	public void setName(String name) {
		this.name = name;
	}

	public List<PropertyDescriptor> getColumns() {
		return columns;
	}

	public void setColumns(List<PropertyDescriptor> columns) {
		this.columns = columns;
	}

	public boolean isIdAuto() {
		return idAuto;
	}

	public void setIdAuto(boolean idAuto) {
		this.idAuto = idAuto;
	}
	
	public PropertyDescriptor getIdProperty() {
		return idProperty;
	}

	public void setIdProperty(PropertyDescriptor idProperty) {
		this.idProperty = idProperty;
	}
	
	public Object getPropertyValue(PropertyDescriptor pd,Object target){
		Method method = pd.getReadMethod();
		try {
			return method.invoke(target);
		} catch (IllegalAccessException e) {
			throw new DbException(e);
		} catch (IllegalArgumentException e) {
			throw new DbException(e);
		} catch (InvocationTargetException e) {
			throw new DbException(e);
		}
	}
	
	public Object setPropertyValue(PropertyDescriptor pd,Object target,Object value){
		Method method = pd.getWriteMethod();
		try {
			return method.invoke(target,value);
		} catch (IllegalAccessException e) {
			throw new DbException(e);
		} catch (IllegalArgumentException e) {
			throw new DbException(e);
		} catch (InvocationTargetException e) {
			throw new DbException(e);
		}
	}
	
}
